package com.ala4.oxcafe.boot.handler;

import com.ala4.oxcafe.common.utils.ResponseWriter;
import com.ala4.oxcafe.domain.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * 登录失败处理类
 *
 * @author PING
 * @version 1.0
 * @date 2024/12/24 16:07
 */
@Slf4j
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败,原因：{}", exception.getMessage());

        String requestURI = request.getRequestURI();
        R<?> fail = R.fail(exception.getMessage(), requestURI);

        fail.setError(exception.getMessage());

        if (exception instanceof BadCredentialsException) {
            // 用户密码错误 || 用户不存在
            fail.setMessage("用户不存在或密码错误");
        }
        if (exception instanceof DisabledException) {
            fail.setMessage("用户已失效,请联系管理员");
        }
        // 写出
        ResponseWriter.write(response, fail);
    }
}
